qui(
    function (require, exports, module) {
        Zhibo.Grid = function (options) {
            this.dao = Zhibo.Dao;
            this.task = Zhibo.Task;
            this.config = Zhibo.Config;
            this.options = options || {};
        };
        Com.inherits(Zhibo.Grid, Ancestor.Grid).extend({
            runList: function (options, callback) {
                var self = this;
                self.initDialog();
                self.$grid = $('#list');
                self.$ipListGrid = $('#ipList');
                self.$logListGrid = $('#logList');
                self.$recordListGrid = $('#recordList');

                var taskArr = [];
                taskArr.push(self.task.getSourceIp($("div.user a.name").html(), this.dao.cfgName.getSourceIp));
                taskArr.push(self.task.getLogType(self.dao.cfgName.LogType));
                self.initListGrid();
                self.initIpListGrid();
                self.initLogListGrid();
                self.initRecordListGrid();
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    console.log("load complete");
                    self.initAuthBaseView();
                    self.initAuthSeniorView();
                    self.initSuggest();
                    self.bindBasicEvent();
                    self.config.PageBean = Zhibo.Util.createPageBean();
                    self.config.IpPageBean = Zhibo.Util.createPageBean();
                    self.jumpFromZzd();
                    self.query();
                })
                self.initAuth();
            },
            jumpFromZzd:function () {
                var ip=location.search;
                var self =this;
                if(ip!="") {
                    ip = ip.slice(1).split("=")[1];
                    var exist = 0 ;
                    $("#QueryContainer").find("select[name=ip]").children().each(function(i,elem){
                        if($(elem).val() == ip){
                            exist=1;
                            $(elem).attr('selected',true)
                        };
                    });
                    if(exist==0){
                        $("#QueryContainer").find("select[name=ip]").append($('<option>').val(ip).html(ip).attr('selected',true));
                        self.showNoData(self.$grid);
                    }
                }
            },

            initAuth: function () {
                var self = this;
                self.readyCount = 0;
                self.finalCount = 6;
                self.initOver = false;
                auth.getAuthData({tips: 1, url: '/epg/auth/base'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_BASE = true;
                    }
                    self.phaseOver();
                })
                auth.getAuthData({tips: 1, url: '/epg/auth/senior'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_SENIOR = true;
                    }
                    self.phaseOver();
                })
                auth.getAuthData({tips: 1, url: '/epg/auth/region/cq'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_REGION_CQ = true;
                    }
                    self.phaseOver();
                })
                auth.getAuthData({tips: 1, url: '/epg/auth/region/sh'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_REGION_SH = true;
                    }
                    self.phaseOver();
                })
                auth.getAuthData({tips: 1, url: '/epg/auth/region/bj'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_REGION_BJ = true;
                    }
                    self.phaseOver();
                })
                auth.getAuthData({tips: 1, url: '/epg/auth/region/tw'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_REGION_TW = true;
                    }
                    self.phaseOver();
                })
            },
            phaseOver: function () {
                var self = this;
                self.readyCount++;
                if (!self.initOver && self.readyCount == self.finalCount) {
                    self.initOver = true;
                    EpgWeb.ajaxQueue.startLoad();
                }
            },
            initAuthBaseView: function () {

            },
            initAuthSeniorView: function () {
                var self = this;
                if (self.config.AUTH_SENIOR) {
                    $("#auth_partner_div").show();
                    $("button[name=createBtn]").show();
                    $("button[name=ipControl]").show();
                } else {
                    $("#auth_partner_div").hide();
                    $("button[name=createBtn]").hide();
                    $("button[name=ipControl]").hide();
                }
            },

            getParam: function () {
                var params = {};
                params.username = $("div.user a.name").html();
                params.type = $("#myTab li.active").attr("value");
                var queryParent = $("#QueryContainer")
                if (queryParent.find("select[name=freeType]").val() != "all") {
                    params.freeType = $("select[name=freeType]").val()
                }
                if (queryParent.find("select[name=channel_status]").val() != "all") {
                    params.channel_status = $("select[name=channel_status]").val()
                }
                if (queryParent.find("select[name=ip]").val() != "all" && queryParent.find("select[name=ip]").val() != "all-limit") {
                    params.ip = $("select[name=ip]").val()
                }
                if (queryParent.find("input[name=channel_code]").val().length > 0) {
                    params.channel_code = $("input[name=channel_code]").val()
                }
                if (queryParent.find("input[name=channel_name]").val().length > 0) {
                    params.channel_name = $("input[name=channel_name]").val()
                }
                params.from_client = true;
                params._ = new Date().getTime();
                console.log(JSON.stringify(params));
                return params;
            },
            initListGrid: function (options, callback) {
                var self = this;
                // var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.TABLE_LIST);
                options = $.extend(true, {}, gridConfig, options);
                self.$grid.jqGrid(options);
            },

            initIpListGrid: function (options, callback) {
                var self = this;
                //   var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.TABLE_IP);
                options = $.extend(true, {}, gridConfig, options);
                self.$ipListGrid.jqGrid(options);
                $("#ip_pager_left").css({"width": "100px"})
            },

            initLogListGrid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LOG);
                var options = $.extend(true, {}, gridConfig);
                self.$logListGrid.jqGrid(options);
            },
            initRecordListGrid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_RECORD);
                var options = $.extend(true, {}, gridConfig);
                self.$recordListGrid.jqGrid(options);
            },
            showNoData: function (jqGridTarget) {
                var re_records = jqGridTarget.getGridParam('records');
                var parentElement = jqGridTarget.parent();
                var norecordElement = parentElement.find(".norecords")
                if (re_records == 0 || re_records == null) {
                    if (norecordElement.html() == null) {
                        parentElement.append('<div class="norecords">没有符合数据</div>');
                        norecordElement.hide();
                    }
                    norecordElement.show();
                } else {
                    norecordElement.hide();
                }
            },

            bindBasicEvent: function () {
                var self = this;
                $("button[name=createBtn]").bind("click", function (event) {
                    Zhibo.Util.addElement();
                })
                $("button[name=ipControl]").bind("click", function (event) {
                    $("#ipConfigDiv").dialog("open");
                })
                $("button[name=channelQuery]").bind("click", function (event) {
                    self.query();
                })
                $("#resetFrm").bind("click", function (event) {
                    $("form[name=basicFrm]")[0].reset();
                    $("select[name=server_region]").change();
                    //$("form[name=basicFrm]")
                })

                $("#ip-list").bind("click", function (event) {
                    self.ipQuery();
                })
                $("select[name=server_region]").bind("change", function (event) {
                    var selectJDom = $("#filter_source_ip");
                    selectJDom.html("");
                    var responseData = self.dao.getSourceIp();
                    var eqVal = event.currentTarget.value == "all" ? null : parseInt(event.currentTarget.value);
                    if (null == eqVal) {
                        $("<option value='all'>全部</option>").appendTo(selectJDom);
                    } else {
                        $("<option value='all-limit'>全部</option>").appendTo(selectJDom);
                    }
                    if (responseData != null && responseData.response != null && responseData.response.list != null) {
                        $.each(responseData.response.list, function (i, obj) {
                            if (eqVal == null || eqVal == obj[1]) {
                                $("<option>", {
                                    value: obj[0],
                                    html: Zhibo.Config.IP_LINK_AREA[obj[0]]
                                }).appendTo(selectJDom);
                            }
                        })
                    }
                })
                $("select[name=server_region]").change();
                $("select[name=server_region2]").bind("change", function (event) {
                    var selectJDom = $("#sourceiplist")
                    selectJDom.html("");
                    var responseData = self.dao.getSourceIp();
                    var eqVal = event.currentTarget.value == "all" ? null : parseInt(event.currentTarget.value);
                    if (eqVal == null) {
                        $("<option value=''>请选择</option>").appendTo(selectJDom);
                    }
                    if (responseData != null && responseData.response != null && responseData.response.list != null) {
                        $.each(responseData.response.list, function (i, obj) {
                            if (eqVal == null || eqVal == obj[1]) {
                                $("<option>", {
                                    value: obj[0],
                                    html: Zhibo.Config.IP_LINK_AREA[obj[0]]
                                }).appendTo(selectJDom);
                            }
                        })
                    }
                })
                $("select[name=server_region2]").change();
            },

            query: function () {
                var self = this;
                self.dao.getList(self.getParam(), function (data) {
                    var retValue = null;
                    if (data.code === 200 && data.response != null && data.response.list != null) {
                        if (self.config.WAIT_ADD_DATA != null) {
                            var waitData = self.config.WAIT_ADD_DATA;
                            self.config.WAIT_ADD_DATA = null;
                            Zhibo.Util.submitAddLog(data.response.list, waitData);

                        }
                        if ($("select[name=ip]").val() == "all-limit") {
                            self.config.PageBean.setNewData(self.doRegionFilter(data.response.list));
                        } else {
                            self.config.PageBean.setNewData(data.response.list);
                        }

                    } else {
                        self.config.PageBean.setNewData([]);
                    }
                    retValue = self.config.PageBean.getCur();
                    self.$grid[0].addJSONData(retValue)
                    self.showNoData(self.$grid);
                });
            },
            doRegionFilter: function (dataArr) {
                var regionValue = Zhibo.Config.REGION_LIST[ parseInt($("select[name=server_region]").val())];
                var areaSign = null;
                var newArr = [];
                $.each(dataArr, function (i, element) {
                    areaSign = Zhibo.Config.IP_LINK_AREA[ element.channel_ip ]
                    if (areaSign != null && areaSign.indexOf(regionValue) != -1) {
                        newArr.push(element)
                    }
                })
                return newArr;
            },
            ipQuery: function () {
                var self = this;
                self.dao.getIpList({type: $("#myTab li.active").attr("value"), area: ""}, self.fillIpTable);
            },
            recordQuery: function () {
                var self = this;
                var channelId = $("input[name=record_channel_id]").val();
                self.$recordListGrid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: {channelId: parseInt(channelId)}
                }).trigger("reloadGrid");
            },
            initDialog: function () {
                var self = this;
                $("#modifyDiv").dialog({
                    title: "打点项目明细",
                    autoOpen: false,
                    width: 500,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    open: function () {
                        $("#modifyDiv").find("form").trigger("reset");
                        $("#modifyDiv").find("input[name=channel_code]").removeAttr("readonly");
                        $("#modifyDiv").find("input[name=channel_addr]").removeAttr("readonly");
                        $("#modifyDiv").find("select[name=server_region2]").change();
                    }
                });

                $("#ipConfigDiv").dialog({
                    title: "ip分组管理",
                    autoOpen: false,
                    width: 700,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    open: function () {
                        $('#ipConfigDiv').show();
                        self.ipQuery();
                    }
                });

                $("#codeDetail").dialog({
                    title: "编码详情",
                    autoOpen: false,
                    width: 500,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    open: function () {
                        $('#codeDetail').show();
                        self.fillCodeDetail();
                    }
                });

                $("#vodLogDiv").dialog({
                    title: "历史记录",
                    autoOpen: false,
                    width: 900,
                    height: 600,
                    modal: true,
                    dialogClass: 'alert'
                });
                self.initRecordDlg();
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            },

            initRecordDlg: function () {
                var self = this;
                $("#vodRecordDiv").dialog({
                    title: "定时收录设定",
                    autoOpen: false,
                    width: 900,
                    height: 600,
                    modal: true,
                    dialogClass: 'alert'
                });
                EpgWeb.Util.bindDate("record_start_time", "record_end_time");
                $("button[name=record-list]").on("click", function (event) {
                    self.recordQuery();
                })
                $("button[name=record-clear-list]").on("click", function (event) {
                    Zhibo.Util.delRecord();
                })
                $("button[name=record-clear-form]").on("click", function (event) {
                    Zhibo.Util.cleanRecordForm();
                })
            },

            initSuggest: function () {
                var locationSuggest = {
                    options: {
                        source: "/api/redirect",
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var params = term.length == 0 ? {types: "province,city", domestic: 1} : {word: term, types: "province,city", domestic: 1};
                            var requestData = {url: "http://lego.iqiyi.com/suggest/location-type", type: "get", params: params, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },

                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["name"];
                                itemData["value"] = item["name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },

                        template: function (item) {
                            return item["label"];
                        }
                    }
                }
                $("input[name=location]").suggest(locationSuggest.options);

                var emailSuggest = {
                    options: {
                        source: "/api/redirect",
                        method: "post",
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: Zhibo.Constant.thirdUrl_query_user, type: "get", params: {email: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["email"];
                                itemData[options.labelKey] = item["userName"];
                                itemData["value"] = item["userName"]
                                itemData["email"] = item["email"];
                                itemData["uid"] = item["uid"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.id + "(" + item.label + ")";
                        }
                    }
                }
                $("input[name=project_workers]").suggest(emailSuggest.options);
            },
            fillIpTable: function (data) {
                var jqGrid = $("#ipList");
                if (data.code === 200 && data.response != null && data.response.list != null) {
                    var formatterData = [];
                    $.each(data.response.list, function (i, element) {
                        formatterData.push({ip: element[1], region: element[2], id: element[0]});
                    });
                    Zhibo.Config.IpPageBean.setNewData(formatterData);
                    jqGrid[0].addJSONData(Zhibo.Config.IpPageBean.getCur())
                }
            },
            fillCodeDetail: function () {
                var self = this;
                var $size = $("#size"),
                    $codeType = $("#codeType"),
                    $gpuPipeline = $("#gpuPipeline"),
                    $delog = $("#delog"),
                    $v720p = $("#v720p"),
                    $v1080p = $("#v1080p"),
                    $dolby = $("#dolby"),
                    $panoType = $("#panoType"),
                    $zhiboVersion = $("#zhiboVersion"),
                    $bianmaqiVersion = $("#bianmaqiVersion");

                this.dao.version({}, function (data) {
                    if (data != null) {
                        var versions = data.split("|");
                        $zhiboVersion.val(versions[0]);
                        $bianmaqiVersion.val(versions[1]);
                    }
                });

                this.dao.channelInfo({from_client: "true", channel_code: $("#code").val()}, function (data) {
                    if (data != null) {
                        var info = data[0];
                        $size.val(info.dpi);
                        $codeType.val(Zhibo.Config.ENCODE_TYPE[info.encode_type]);
                        if (info.encode_type == 1) {
                            $('#gpuDiv').css('display', 'block');
                            $gpuPipeline.val(Zhibo.Config.ENCODE_INDEX[info.encode_index]);
                        } else {
                            $('#gpuDiv').css('display', 'none');
                            $gpuPipeline.val('');
                        }
                        $delog.val(Zhibo.Config.ANSWER[info.delog]);
                        $v720p.val(Zhibo.Config.ANSWER[info.v720p]);
                        $v1080p.val(Zhibo.Config.ANSWER[info.v1080p]);
                        $dolby.val(Zhibo.Config.ANSWER[info.dolby]);
                        $panoType.val(Zhibo.Config.ENCODE_PANOTYPE[info.panoType]);
                    }
                });

                this.dao.dotLoad({from_client: "true", channel_code: $("#code").val()}, function (data) {
                    if (data != null) {
                        var load = data.load;
                        var lavg_1 = load.lavg_1,
                            lavg_5 = load.lavg_5,
                            lavg_15 = load.lavg_15,
                            cpu = load.CPU,
                            K1 = load.K1;
                        var warnning = "<span style='color:#F00'>@warnning</span>";
                        var html = "CPU核数:" + cpu;
                        html += "</br>一分钟负载:";
                        if (parseInt(lavg_1) >= parseInt(cpu)) {
                            html += warnning.replace("@warnning", lavg_1);
                        } else {
                            html += lavg_1;
                        }
                        html += "</br>五分钟负载:";
                        if (parseInt(lavg_5) >= parseInt(cpu)) {
                            html += warnning.replace("@warnning", lavg_5);
                        } else {
                            html += lavg_5;
                        }
                        html += "</br>十五分钟负载:";
                        if (parseInt(lavg_15) >= parseInt(cpu)) {
                            html += warnning.replace("@warnning", lavg_15);
                        } else {
                            html += lavg_15;
                        }
                        html += "</br>是否有K1卡:" + Zhibo.Config.ANSWER[K1];
                        $("#dotLoad").html(html);
                    }
                });
            }
        })
    }
);